<template>
  <div class="chat-box">
    <div class="chat-header">
      <span class="chat-title">聊天</span>
      <el-badge v-if="unreadCount > 0" :value="unreadCount" class="unread-badge" />
    </div>
    
    <div ref="messagesContainer" class="chat-messages">
      <div
        v-for="message in messages"
        :key="message.messageId"
        :class="['message-item', { 'message-sent': message.senderId === currentUserId.value }]"
      >
        <div class="message-content">
          <div class="message-header">
            <span class="message-username">{{ message.senderUsername }}</span>
            <span class="message-time">{{ formatTime(message.createdAt) }}</span>
          </div>
          <div class="message-text">{{ message.content }}</div>
        </div>
      </div>
      <div v-if="loading" class="loading-more">加载中...</div>
      <div v-if="messages.length === 0 && !loading" class="empty-messages">暂无消息</div>
    </div>
    
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="3"
        placeholder="输入消息..."
        @keydown.ctrl.enter="sendMessage"
        @keydown.meta.enter="sendMessage"
      />
      <div class="chat-actions">
        <el-button type="primary" :loading="sending" @click="sendMessage">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { chatApi } from '../api/chat'
import { getChatSocket } from '../utils/chatSocket'
import { useAuthStore } from '../store/auth'

interface Message {
  messageId: string
  contextType: string
  contextId: string
  senderId: string
  senderUsername: string
  receiverId: string
  receiverUsername: string
  content: string
  messageType: string
  isRead: boolean
  createdAt: string
}

interface Props {
  contextType?: string
  contextId: string
  receiverId: string
  receiverUsername?: string
}

const props = withDefaults(defineProps<Props>(), {
  contextType: 'c2c_trade'
})

const authStore = useAuthStore()
const currentUserId = computed(() => authStore.userInfo?.id || '')

const messages = ref<Message[]>([])
const inputMessage = ref('')
const sending = ref(false)
const loading = ref(false)
const unreadCount = ref(0)
const messagesContainer = ref<HTMLElement | null>(null)

const chatSocket = getChatSocket()

// 加载历史消息
const loadMessages = async (page: number = 1) => {
  try {
    loading.value = true
    const response = await chatApi.getMessages({
      contextType: props.contextType,
      contextId: props.contextId,
      page,
      pageSize: 50
    })
    
    if (page === 1) {
      messages.value = response.list || []
    } else {
      messages.value = [...(response.list || []), ...messages.value]
    }
    
    await nextTick()
    scrollToBottom()
  } catch (error: any) {
    ElMessage.error(error.message || '加载消息失败')
  } finally {
    loading.value = false
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || sending.value) {
    return
  }

  const content = inputMessage.value.trim()
  inputMessage.value = ''

  try {
    sending.value = true
    
    // 通过Socket发送（实时）
    chatSocket.sendMessage(
      props.contextType,
      props.contextId,
      props.receiverId,
      content,
      'text'
    )
  } catch (error: any) {
    ElMessage.error(error.message || '发送消息失败')
    inputMessage.value = content // 恢复输入
  } finally {
    sending.value = false
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (time: string) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / 60000)
  
  if (minutes < 1) {
    return '刚刚'
  } else if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else {
    return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
  }
}

// Socket事件处理
const handleNewMessage = (message: Message) => {
  // 只添加当前上下文的消息
  if (message.contextType === props.contextType && message.contextId === props.contextId) {
    messages.value.push(message)
    nextTick(() => {
      scrollToBottom()
    })
    
    // 如果是接收的消息，标记为已读
    if (message.receiverId === currentUserId.value) {
      chatSocket.markAsRead(message.messageId)
    }
  }
}

const handleMessageSent = (message: Message) => {
  // 消息发送成功，添加到列表
  if (message.contextType === props.contextType && message.contextId === props.contextId) {
    const exists = messages.value.find(m => m.messageId === message.messageId)
    if (!exists) {
      messages.value.push(message)
      nextTick(() => {
        scrollToBottom()
      })
    }
  }
}

const handleError = (error: any) => {
  ElMessage.error(error.message || '聊天服务错误')
}

// 加载未读数量
const loadUnreadCount = async () => {
  try {
    const response = await chatApi.getUnreadCount({
      contextType: props.contextType,
      contextId: props.contextId
    })
    unreadCount.value = response.unreadCount || 0
  } catch (error) {
    // 忽略错误
  }
}

// 监听contextId变化
watch(() => props.contextId, (newId, oldId) => {
  if (newId && newId !== oldId) {
    messages.value = []
    chatSocket.leaveRoom()
    initChat()
  }
}, { immediate: false })

// 初始化聊天
const initChat = () => {
  if (!props.contextId) {
    return
  }

  // 连接Socket
  chatSocket.connect()
  
  // 加入房间
  chatSocket.joinRoom(props.contextType, props.contextId)
  
  // 加载历史消息
  loadMessages(1)
  
  // 加载未读数量
  loadUnreadCount()
  
  // 监听Socket事件
  chatSocket.on('newMessage', handleNewMessage)
  chatSocket.on('messageSent', handleMessageSent)
  chatSocket.on('error', handleError)
}

onMounted(() => {
  initChat()
})

onUnmounted(() => {
  // 离开房间
  chatSocket.leaveRoom(props.contextType, props.contextId)
  
  // 移除事件监听
  chatSocket.off('newMessage', handleNewMessage)
  chatSocket.off('messageSent', handleMessageSent)
  chatSocket.off('error', handleError)
})
</script>

<style scoped lang="scss">
.chat-box {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fff;
}

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #f5f7fa;
  
  .chat-title {
    font-weight: 600;
    font-size: 14px;
  }
  
  .unread-badge {
    margin-left: 8px;
  }
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #fafafa;
  
  .message-item {
    margin-bottom: 16px;
    
    &.message-sent {
      .message-content {
        margin-left: auto;
        margin-right: 0;
        background: #409eff;
        color: #fff;
        
        .message-header {
          color: rgba(255, 255, 255, 0.8);
        }
      }
    }
    
    .message-content {
      max-width: 70%;
      padding: 8px 12px;
      border-radius: 8px;
      background: #fff;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
      
      .message-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 4px;
        font-size: 12px;
        color: #909399;
        
        .message-username {
          font-weight: 500;
        }
        
        .message-time {
          margin-left: 8px;
        }
      }
      
      .message-text {
        font-size: 14px;
        line-height: 1.5;
        word-wrap: break-word;
      }
    }
  }
  
  .loading-more,
  .empty-messages {
    text-align: center;
    color: #909399;
    padding: 20px;
    font-size: 14px;
  }
}

.chat-input {
  padding: 12px;
  border-top: 1px solid #e4e7ed;
  background: #fff;
  
  .chat-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 8px;
  }
}
</style>

